<?php

namespace app\merchant\controller;

use app\common\lib\Page;
use app\common\lib\MyController;
use app\merchant\model\TpAssets;
use app\merchant\model\TpAssetsDetail;
use app\merchant\model\MerchantConfig;
use app\merchant\model\BorrowRequest;
use app\merchant\model\TpAssetsPool;
use app\merchant\model\AssetNumberIncrease;
use \think\Db;
use app\common\lib\Constant;
use app\merchant\model\TpMerchant;
use app\merchant\model\TpBorrow;
use think\Validate;

/**
 * 打包资产
 */
class Assets extends MyController
{

    /**
     * 资产列表
     * @return type
     */
    public function index()
    {
        $user_id = $this->_Uid;

        //搜索条件
        $page = input('page', 1);
        $code = input('code', '');
        $name = input('name', '');
        $type = input('type', 0);
        $status = input('status', 0);
        $duration = input('duration', 0);
        $capital_min = input('capital_min', '');
        $capital_max = input('capital_max', '');

        $where = ['merchant_id' => ['=', $user_id]];
        $where_more = [];
        if ($code) { //资产编号
            $where['code'] = ['=', $code];
        }
        if ($name) { //资产名称
            $where['name'] = ['like', '%' . $name . '%'];
        }
        if ($type) { //资产类型
            $where['type'] = ['=', $type];
        }
        if ($status) { ////资产状态
            $where['status'] = ['=', $status];
        }
        if ($duration) { //放款期限
            $where['duration'] = ['=', $duration];
        }
        if ($capital_min) { //资产总额最小值
            $where['capital'] = ['>=', $capital_min];
        }
        if ($capital_max) { //资产总额最大值
            $where_more['capital'] = ['<=', $capital_max];
        }

        $count = TpAssets::where($where)->where($where_more)->count();
        $list = TpAssets::where($where)->where($where_more)->page($page, Constant::PAGE_SIZE_MID)->order('update_time DESC')->select();

        if ($list) {
            foreach ($list as $key => $val) {

                $list[$key]['type'] = TpAssets::getTypeName($val['type']); //资产类型
                $list[$key]['repayment_type'] = TpAssets::getRepaymentTypeName($val['repayment_type']); //还款方式
                switch ($val['status']) {
                    case TpAssets::STATUS_BACK:
                        $list[$key]['status_name'] = TpAssets::getStatusName($val['status']) . ':' . $val['remarks'];
                        break;
                    case TpAssets::STATUS_CHECK:
                        $list[$key]['status_name'] = TpAssets::getStatusName($val['status']);
                        break;
                    case TpAssets::STATUS_TO_BE_RAISE:
                        $list[$key]['status_name'] = TpAssets::getStatusName($val['status']);
                        break;
                    case TpAssets::STATUS_RAISING:
                        //已募集金额
                        $raised = TpAssetsPool::where('assets_id', '=', $val['id'])->sum('raised');
                        //待募集额度
                        $left_money = $val['capital'] - $raised;
                        $list[$key]['status_name'] = TpAssets::getStatusName($val['status']) . ':' . number_format($left_money, 2); //剩余待募集
                        break;
                    case TpAssets::STATUS_DONE:
                        $list[$key]['status_name'] = TpAssets::getStatusName($val['status']);
                        break;
                    default:
                        break;
                }
            }
        }

        //分页
        $page_class = new Page();
        $paginator = $page_class->pages($count, Constant::PAGE_SIZE_MID, $page);

        //放款期限列表
        $term_list = MerchantConfig::where('user_id', '=', $user_id)->where('is_delete', '=', 0)->distinct(true)->column('term');
        sort($term_list); //排序下，不然太丑了
        //添加资产-根据配置展示
        $show_type = TpMerchant::where('user_id', '=', $user_id)->value('show_type');
        $show_types = explode(',', $show_type);
        sort($show_types); //先排好序
        $type_list = [];
        //弄成键值对的方式
        foreach ($show_types as $val) {
            $type_list[$val] = TpAssets::getTypeName($val);
        }

        $assign = [
            'code' => $code,
            'name' => $name,
            'type' => $type,
            'status' => $status,
            'duration' => $duration,
            'capital_min' => $capital_min,
            'capital_max' => $capital_max,
            'list' => $list,
            'paginator' => $paginator,
            'term_list' => $term_list,
            'type_list' => $type_list,
            'status_list' => TpAssets::getStatusList(),
        ];
        unset($term_list); //sort排序后用完就卸载掉

        $this->assign($assign);
        return view('Assets/index');
    }

    /**
     * 资产详情
     * @return type
     */
    public function show()
    {
        $user_id = $this->_Uid;

        $id = input('id/d');
        //资产
        $assets = TpAssets::find($id);
        //校验
        if (!$assets) {
            return $this->messageView('无此资产包');
        }

        $assets['status_name'] = TpAssets::getStatusName($assets['status']);
        $assets['capital'] = number_format($assets['capital'], 2);

        $this->assign('assets', $assets);

        //借款人详情
        $field = 'a.duration, a.interest_rate, ad.amount, tu.real_name, tu.user_phone, tu.idcard, br.repayment_type, br.money, br.batch_number, br.duration as br_duration,brd.extra_filed, ta.borrow_money';
        $detail = TpAssets::alias('a')
                ->join('tp_assets_details ad', 'a.id = ad.assets_id')
                ->join('tp_user tu', 'ad.borrower_uid = tu.uid')
                ->join('tp_borrow_request br', 'ad.request_id = br.id')
                ->join('tp_borrow_request_detail brd', 'ad.request_id = brd.borrow_request_id', 'LEFT')
                ->join('tp_account ta', 'ad.borrower_uid = ta.user_id', 'LEFT')
                ->where('a.id', '=', $id)
                ->where('ad.delete_status', '=', 0)
                ->field($field)
                ->select();
        //在贷余额
        $money_max = 0;
        if ($assets['type'] == TpAssets::TYPE_CAR || $assets['type'] == TpAssets::TYPE_CONSUME) {
            $money_max = Constant::INDIVIDUAL_MONEY_MAX;
        } else {
            $money_max = Constant::ENTERPRISE_MONEY_MAX;
        }
        foreach ($detail as $key => $val) {
            $detail[$key]['left_money'] = number_format($money_max - $val['borrow_money']); //在贷余额

            $extra_filed = json_decode($val['extra_filed'], TRUE);
            //数据结构修改了，做法也得修改 2018-05-10
            $items = [];
            foreach ($extra_filed as $extra_val) {
                foreach ($extra_val['items'] as $value) {
                    $items[$value['field']] = $value['value'];
                }
            }
            if ($assets['type'] == TpAssets::TYPE_CAR) { //车贷
                //$detail[$key]['car_price'] = isset($extra_filed['car_price']) ? $extra_filed['car_price'] : '';
                //$detail[$key]['percent'] = isset($extra_filed['percent']) ? $extra_filed['percent'] : '';
                $detail[$key]['car_price'] = isset($items['car_price']) ? $items['car_price'] : '';
                $detail[$key]['percent'] = isset($items['percent']) ? $items['percent'] : '';
            } elseif ($assets['type'] == TpAssets::TYPE_ENTERPRISE) { //企业贷
                //$detail[$key]['company_name'] = isset($extra_filed['company_name']) ? $extra_filed['car_price'] : '';
                //$detail[$key]['telephone'] = isset($extra_filed['telephone']) ? $extra_filed['telephone'] : '';
                $detail[$key]['company_name'] = isset($items['company_name']) ? $items['car_price'] : '';
                $detail[$key]['telephone'] = isset($items['telephone']) ? $items['telephone'] : '';
            }
        }
        $this->assign('detail', $detail);

        //募集信息
        $have_raised = TpAssetsPool::getRaisedSum($id, [TpAssetsPool::STATUS_PAYING, TpAssetsPool::STATUS_PAID], 1); //已募集
        $wait_raised = TpAssetsPool::getRaisedSum($id, TpAssetsPool::STATUS_UNSOLD); //待募集
        $raising = TpAssetsPool::getRaisedSum($id, TpAssetsPool::STATUS_RAISING); //募集中
        $this->assign('ed', $have_raised);
        $this->assign('no', $wait_raised);
        $this->assign('ing', $raising);
        $field2 = 'b.title, b.gregate_amount, b.interest_rate, b.duration, b.status, b.repayment_end_time, b.is_immediately_loan, b.full_time, a.repayment_type, br.real_repay_time';
        $info = TpAssets::alias('a')
                ->join('tp_assets_pool ap', 'a.id = ap.assets_id')
                ->join('tp_borrow b', 'ap.borrow_id = b.id')
                ->join('tp_borrow_repay br', 'b.id = br.borrow_id', 'LEFT')
                ->where('a.id', '=', $id)
                ->where('b.status', 'in', [TpBorrow::STATUS_NEW, TpBorrow::STATUS_INVESTOR, TpBorrow::STATUS_FULL, TpBorrow::STATUS_PAY_SUCCESS, TpBorrow::STATUS_REPAYMENT_PAY_SUCCESS])
                ->group('b.id')
                ->field($field2)
                ->select();

        foreach ($info as $key => $val) {
            $info[$key]['repayment_type'] = TpAssets::getRepaymentTypeName($val['repayment_type']); //还款方式
            $info[$key]['pay_money'] = intval($val['gregate_amount'] + $val['gregate_amount'] * $val['interest_rate'] * $val['duration'] / 36000);//interest_rate没有按百分比
            $info[$key]['status'] = TpAssets::getStatusName($val['status']);
            //到期日
            if ($val['is_immediately_loan'] == 1) {
                $info[$key]['dead_line'] = $val['repayment_end_time'];
            } else {
                $info[$key]['dead_line'] = $val['full_time'] + $val['duration'];
            }
        }

        $this->assign('info', $info);

        //还款方式
        $repayment_type_list = TpAssets::getRepaymentTypeList();
        $this->assign('repayment_type_list', $repayment_type_list);

        return view('Assets/show');
    }

    /**
     * 编辑基础信息页面
     * @return type
     */
    public function editMain()
    {
        $user_id = $this->_Uid;

        $id = input('id/d');
        //资产
        $assets = TpAssets::find($id);
        //校验
        if (!$assets) {
            return $this->messageView('无此资产包');
        }
        $assets['capital'] = number_format($assets['capital'], 2);

        $this->assign('assets', $assets);

        //总成本利率（这个是作为修改的比较的基准，修改后的数据不能小于它）
        $merchant_config = MerchantConfig::where('user_id', '=', $user_id)->where('is_delete', '=', 0)->select();
        //双重维度，类型和期限才能确定列表中的总成本利率
        $interest_rate = 0;
        foreach ($merchant_config as $mc) {
            //展业和期限同时满足条件才行
            if ($mc['category'] == $assets['type'] && $assets['duration'] == $mc['term']) {
                $interest_rate = $mc['interest_rate'];
                break; //及时退出当前循环
            }
        }
        $this->assign('interest_rate', $interest_rate);

        //借款人详情
        $field = 'a.duration, ad.amount, tu.real_name, tu.user_phone, tu.idcard, br.batch_number, br.repayment_type, br.money, br.duration as br_duration,brd.extra_filed, ta.borrow_money';
        $detail = TpAssets::alias('a')
                ->join('tp_assets_details ad', 'a.id = ad.assets_id')
                ->join('tp_user tu', 'ad.borrower_uid = tu.uid')
                ->join('tp_borrow_request br', 'ad.request_id = br.id')
                ->join('tp_borrow_request_detail brd', 'ad.request_id = brd.borrow_request_id', 'LEFT')
                ->join('tp_account ta', 'ad.borrower_uid = ta.user_id', 'LEFT')
                ->where('a.id', '=', $id)
                ->where('ad.delete_status', '=', 0)
                ->field($field)
                ->select();
        //在贷余额
        $money_max = 0;
        if ($assets['type'] == TpAssets::TYPE_CAR || $assets['type'] == TpAssets::TYPE_CONSUME) {
            $money_max = Constant::INDIVIDUAL_MONEY_MAX;
        } else {
            $money_max = Constant::ENTERPRISE_MONEY_MAX;
        }
        foreach ($detail as $key => $val) {
            $detail[$key]['left_money'] = number_format($money_max - $val['borrow_money']); //在贷余额

            $extra_filed = json_decode($val['extra_filed'], TRUE);
            //数据结构修改了，做法也得修改 2018-05-10
            $items = [];
            foreach ($extra_filed as $extra_val) {
                foreach ($extra_val['items'] as $value) {
                    $items[$value['field']] = $value['value'];
                }
            }
            if ($assets['type'] == TpAssets::TYPE_CAR) { //车贷
                //$detail[$key]['car_price'] = isset($extra_filed['car_price']) ? $extra_filed['car_price'] : '';
                //$detail[$key]['percent'] = isset($extra_filed['percent']) ? $extra_filed['percent'] : '';
                $detail[$key]['car_price'] = isset($items['car_price']) ? $items['car_price'] : '';
                $detail[$key]['percent'] = isset($items['percent']) ? $items['percent'] : '';
            } elseif ($assets['type'] == TpAssets::TYPE_ENTERPRISE) { //企业贷
                //$detail[$key]['company_name'] = isset($extra_filed['company_name']) ? $extra_filed['car_price'] : '';
                //$detail[$key]['telephone'] = isset($extra_filed['telephone']) ? $extra_filed['telephone'] : '';
                $detail[$key]['company_name'] = isset($items['company_name']) ? $items['car_price'] : '';
                $detail[$key]['telephone'] = isset($items['telephone']) ? $items['telephone'] : '';
            }
        }

        $this->assign('detail', $detail);

        //放款期限
        $term_list = MerchantConfig::where('user_id', '=', $user_id)->where('is_delete', '=', 0)->where('category', '=', $assets['type'])->column('term');
        sort($term_list);
        $this->assign('term_list', $term_list);
        unset($term_list);

        //还款方式
        $repayment_type_list = TpAssets::getRepaymentTypeList();
        $this->assign('repayment_type_list', $repayment_type_list);

        return view('Assets/edit_main');
    }

    /**
     * 修改基础信息
     */
    public function doEditMain()
    {
        $user_id = $this->_Uid;

        $id = input('id/d');
        $name = input('name/s');
        $code = input('code/s');
        $capital = input('capital/f');
        $duration = input('duration/d');
        $interest_rate = input('interest_rate/f');
        $repayment_type = input('repayment_type/d');
        $service_amount_type = input('service_amount_type/d');
        $marketing_fee = input('marketing_fee/f');
        $service_remarks = input('service_remarks/s');
        $contract_time_start = input('contract_time_start/s');
        $contract_time_end = input('contract_time_end/s');
                
        //请求参数校验
        $rule = [
            'id'  => 'require|number',
            'name'  => 'require',
            'code'  => 'require',
            'capital'  => 'require|number',
            'duration'  => 'require|number',
            'interest_rate'  => 'require',
            'repayment_type'  => 'require|number',
            'service_amount_type'  => 'require',
            'contract_time_start'  => 'require',
            'contract_time_end'  => 'require',
        ];

        $data = [
            'id'  => $id,
            'name'  => $name,
            'code'  => $code,
            'capital'  => $capital,
            'duration'  => $duration,
            'interest_rate'  => $interest_rate,
            'repayment_type'  => $repayment_type,
            'service_amount_type'  => $service_amount_type,
            'contract_time_start'  => $contract_time_start,
            'contract_time_end'  => $contract_time_end,
        ];

        $validate = new Validate($rule);
        $result   = $validate->check($data);

        if(!$result){
            $this->error($validate->getError());
        }
        
        $assets = TpAssets::find($id);
        //校验
        if (!$assets) {
            return $this->messageView('无此资产包');
        }

        $data_assets = $data;
        $data_assets['update_time'] = time();
        $data_assets['marketing_fee'] = $marketing_fee;
        $data_assets['service_remarks'] = $service_remarks;
        $data_assets['contract_time_start'] = strtotime($contract_time_start);
        $data_assets['contract_time_end'] = strtotime($contract_time_end);
        $data_assets['status'] = TpAssets::STATUS_CHECK; //状态修改为待审核
//        $data_assets = [
//            'id' => $id,
//            'name' => $name,
//            'code' => $code,
//            'capital' => $capital,
//            'duration' => $duration,
//            'interest_rate' => $interest_rate,
//            'repayment_type' => $repayment_type,
//            'update_time' => time(),
//            'service_amount_type' => $service_amount_type,
//            'marketing_fee' => $marketing_fee,
//            'service_remarks' => $service_remarks,
//            'contract_time_start' => strtotime($contract_time_start),
//            'contract_time_end' => strtotime($contract_time_end),
//            'status' => TpAssets::STATUS_CHECK //状态修改为待审核
//        ];
        //主表添加数据
        TpAssets::update($data_assets);

        $this->success('修改成功', 'Assets/index');
    }

    /**
     * 编辑详细信息页面
     * @return type
     */
    public function editDetail()
    {
        $user_id = $this->_Uid;

        $id = input('id/d');
        //资产
        $assets = TpAssets::find($id);
        //校验
        if (!$assets) {
            return $this->messageView('无此资产包');
        }
        $this->assign('assets', $assets);

        //放款期限
        $term_list = MerchantConfig::where('user_id', '=', $user_id)->where('is_delete', '=', 0)->where('category', '=', $assets['type'])->column('term');
        sort($term_list);
        $this->assign('term_list', $term_list);
        unset($term_list);

        //总成本利率（这个是作为修改的比较的基准，修改后的数据不能小于它）
        $merchant_config = MerchantConfig::where('user_id', '=', $user_id)->where('is_delete', '=', 0)->select();
        //双重维度，类型和期限才能确定列表中的总成本利率
        $interest_rate = 0;
        foreach ($merchant_config as $mc) {
            //展业和期限同时满足条件才行
            if ($mc['category'] == $assets['type'] && $assets['duration'] == $mc['term']) {
                $interest_rate = $mc['interest_rate'];
                break; //及时退出当前循环
            }
        }
        $this->assign('interest_rate', $interest_rate);

        //还款方式
        $repayment_type_list = TpAssets::getRepaymentTypeList();
        $this->assign('repayment_type_list', $repayment_type_list);

        if ($assets['type'] == TpAssets::TYPE_CAR) { //车贷
            return view('Assets/edit_car');
        } elseif ($assets['type'] == TpAssets::TYPE_CONSUME) { //消费贷
            return view('Assets/edit_consume');
        } elseif ($assets['type'] == TpAssets::TYPE_ENTERPRISE) { //企业贷
            return view('Assets/edit_enterprise');
        }
    }

    /**
     * 修改详细信息
     */
    public function doEditDetail()
    {
        $user_id = $this->_Uid;

        $id = input('id/d');
        $name = input('name/s');
        $code = input('code/s');
        $capital = input('capital/f');
        $duration = input('duration/d');
        $interest_rate = input('interest_rate/f');
        $repayment_type = input('repayment_type/d');
        $service_amount_type = input('service_amount_type/d');
        $marketing_fee = input('marketing_fee/f');
        $service_remarks = input('service_remarks/s');
        $contract_time_start = input('contract_time_start/s');
        $contract_time_end = input('contract_time_end/s');
                
        //请求参数校验
        $rule = [
            'id'  => 'require|number',
            'name'  => 'require',
            'code'  => 'require',
            'capital'  => 'require|number',
            'duration'  => 'require|number',
            'interest_rate'  => 'require',
            'repayment_type'  => 'require|number',
            'service_amount_type'  => 'require',
            'contract_time_start'  => 'require',
            'contract_time_end'  => 'require',
        ];

        $data = [
            'id'  => $id,
            'name'  => $name,
            'code'  => $code,
            'capital'  => $capital,
            'duration'  => $duration,
            'interest_rate'  => $interest_rate,
            'repayment_type'  => $repayment_type,
            'service_amount_type'  => $service_amount_type,
            'contract_time_start'  => $contract_time_start,
            'contract_time_end'  => $contract_time_end,
        ];

        $validate = new Validate($rule);
        $result   = $validate->check($data);

        if(!$result){
            $this->error($validate->getError());
        }
        
        $assets = TpAssets::find($id);
        //校验
        if (!$assets) {
            return $this->messageView('无此资产包');
        }

        $now = time();

        // 启动事务
        Db::startTrans();
        try {
            //修改主表数据
            $data_assets = $data;
            $data_assets['update_time'] = $now;
            $data_assets['marketing_fee'] = $marketing_fee;
            $data_assets['service_remarks'] = $service_remarks;
            $data_assets['contract_time_start'] = strtotime($contract_time_start);
            $data_assets['contract_time_end'] = strtotime($contract_time_end);
            $data_assets['status'] = TpAssets::STATUS_CHECK; //状态修改为待审核
//            $data_assets = [
//                'id' => $id,
//                'name' => input('name/s'),
//                'code' => input('code/s'),
//                'capital' => input('capital/f'),
//                'duration' => input('duration/d'),
//                'interest_rate' => input('interest_rate/f'),
//                'repayment_type' => input('repayment_type/d'),
//                'update_time' => $now,
//                'service_amount_type' => input('service_amount_type/d'),
//                'marketing_fee' => input('marketing_fee/f'),
//                'service_remarks' => input('service_remarks/s'),
//                'contract_time_start' => strtotime(input('contract_time_start/s')),
//                'contract_time_end' => strtotime(input('contract_time_end/s')),
//                'status' => TpAssets::STATUS_CHECK //状态修改为待审核
//            ];
            TpAssets::update($data_assets);

            //删除明细表数据
            TpAssetsDetail::where('assets_id', '=', $id)->delete();

            //新增明细表数据
            $ids = input('user_ids/a'); //数组一定要加上/a
            $ids_str = implode(',', $ids);
            $borrows = BorrowRequest::alias('br')
                    ->join('tp_user tu', 'br.borrow_uid = tu.uid')
                    ->where("br.id in ($ids_str)")
                    ->field('br.*, tu.real_name')
                    ->select();
            $data_detail = [];
            $tp_borrow_request_ids = [];
            foreach ($borrows as $borrow) {
                $tp_borrow_request_ids[] = $borrow['id'];
                $temp = [
                    'assets_id' => $id,
                    'request_id' => $borrow['id'],
                    'borrower_name' => $borrow['real_name'],
                    'borrower_uid' => $borrow['borrow_uid'],
                    'amount' => $borrow['money'],
                    'duration' => $borrow['duration'],
                    'created_at' => $now,
                ];
                $data_detail[] = $temp;
            }
            TpAssetsDetail::insertAll($data_detail);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('修改失败，原因如下：' . $e->getMessage());
        }

        $this->success('修改成功', 'Assets/index');
    }

    /**
     * 删除
     * @return type
     */
    public function delete()
    {
        $id = input('id');
        $code = 1;
        $message = '';
        // 启动事务
        Db::startTrans();
        try {
            //主表明细表应该都要删除
            TpAssets::destroy($id);
            TpAssetsDetail::where('assets_id', '=', $id)->delete();

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $code = 0;
            $message = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }

        return parent::returnData($code, $message);
    }

    /**
     * 搜索借款人
     * @return array
     */
    public function borrower()
    {
        $user_id = $this->_Uid;

        $type = input('type/d');
        $batch_number = input('batch_number/s', '');
        $duration = input('duration/d', '');
        $repayment_type = input('repayment_type/d', '');
        $left_money_min = input('left_money_min/f', '');
        $left_money_max = input('left_money_max/f', '');

        //在贷余额要先处理，因为是另一张表的数据
        $where_pool = [];
        $money_max = 0;
        if ($type == TpAssets::TYPE_CAR || $type == TpAssets::TYPE_CONSUME) {
            $money_max = Constant::INDIVIDUAL_MONEY_MAX;
        } else {
            $money_max = Constant::ENTERPRISE_MONEY_MAX;
        }

        $where['br.merchant'] = ['=', $user_id];
        $where['br.status'] = ['=', BorrowRequest::STATUS_YES]; //审核通过
        $where['br.is_file'] = ['=', 0]; //未归档
        $where['br.type'] = ['=', $type]; //展业
        $where_more['ta.borrow_money'] = ['<', $money_max]; //在贷余额大于0
        if ($batch_number) {
            $where['br.batch_number'] = ['=', $batch_number];
        }
        //期限必填
        if ($duration) {
            $where['br.duration'] = ['>=', $duration];
        } else {
            return parent::returnData(0, '请填写期限');
        }
        if ($repayment_type) {
            $where['br.repayment_type'] = ['=', $repayment_type];
        }
        //在贷余额
        if ($left_money_min) {
            $max = $money_max - $left_money_min;
            $where['ta.borrow_money'] = ['<=', $max];
        }
        if ($left_money_max) {
            $min = $money_max - $left_money_max;
            $where_more['ta.borrow_money'] = ['>=', $min];
        }

        $query = BorrowRequest::alias('br')
                ->join('tp_user tu', 'br.borrow_uid = tu.uid')
                ->join('tp_account ta', 'br.borrow_uid = ta.user_id', 'LEFT')
                ->join('tp_borrow_request_detail brd', 'br.id = brd.borrow_request_id', 'LEFT')
                ->where($where)
                ->where($where_more);
        $list = $query->field('br.*, tu.real_name, tu.user_phone, tu.idcard, brd.extra_filed, ta.borrow_money')
                ->order('br.sold_duration desc, br.duration asc, br.create_time asc')
                ->select(); //排序 续借的优先
        //如果没有找到满足条件的数据，提前返回
        if (!$list) {
            return parent::returnData(0, '未找到满足条件的数据');
        }

        //在贷余额
        foreach ($list as $key => $val) {
            $list[$key]['left_money'] = number_format($money_max - $val['borrow_money']); //在贷余额
            $list[$key]['left_duration'] = $val['duration'] - $val['sold_duration']; //剩余期限

            $extra_filed = json_decode($val['extra_filed'], TRUE);
            //数据结构修改了，做法也得修改 2018-05-10
            $items = [];
            foreach ($extra_filed as $extra_val) {
                foreach ($extra_val['items'] as $value) {
                    $items[$value['field']] = $value['value'];
                }
            }
            if ($type == TpAssets::TYPE_CAR) { //车贷
                //$list[$key]['car_price'] = isset($extra_filed['car_price']) ? $extra_filed['car_price'] : '';
                //$list[$key]['percent'] = isset($extra_filed['percent']) ? $extra_filed['percent'] : '';
                $list[$key]['car_price'] = isset($items['car_price']) ? $items['car_price'] : '';
                $list[$key]['percent'] = isset($items['percent']) ? $items['percent'] : '';
            } elseif ($type == TpAssets::TYPE_ENTERPRISE) { //企业贷
                //$list[$key]['company_name'] = isset($extra_filed['company_name']) ? $extra_filed['company_name'] : '';
                //$list[$key]['telephone'] = isset($extra_filed['telephone']) ? $extra_filed['telephone'] : '';
                $list[$key]['company_name'] = isset($items['company_name']) ? $items['company_name'] : '';
                $list[$key]['telephone'] = isset($items['telephone']) ? $items['telephone'] : '';
            }
        }

        //总成本利率 
        $interest_rate = MerchantConfig::where('user_id', '=', $user_id)
                ->where('is_delete', '=', 0)
                ->where('category', '=', $type)
                ->where('term', '=', $duration)
                ->value('interest_rate');

        $data = [
            'interest_rate' => $interest_rate,
            'data' => $list,
            'duration' => $duration,
        ];

        return parent::returnData(1, '成功', $data);
    }

    /**
     * 添加资产
     * @return type
     */
    public function add()
    {
        $user_id = $this->_Uid;

        $type = input('type/d');
        $hidden = input('hidden', 0);
        $batch_number = input('batch_number', '');
        $duration = input('duration', '');
        $repayment_type = input('repayment_type/d', '');
        $left_money_min = input('left_money_min/f', '');
        $left_money_max = input('left_money_max/f', '');

        $this->assign('type', $type);
        $this->assign('hidden', $hidden);
        $this->assign('batch_number', $batch_number);
        $this->assign('duration', $duration);
        $this->assign('repayment_type', $repayment_type);
        $this->assign('left_money_min', $left_money_min);
        $this->assign('left_money_max', $left_money_max);

        //放款期限
        $term_list = MerchantConfig::where('user_id', '=', $user_id)->where('is_delete', '=', 0)->where('category', '=', $type)->column('term');
        sort($term_list);
        $this->assign('term_list', $term_list);

        //资产编号 规则：CEB+年份后两位+月份两位+三位从001开始的自增数现在就是CEB1801001开始
        $year_month = date('y') . date('m');
        // 启动事务
        /*
          Db::startTrans();//防止并发->lock(true)
          try {
          //先查找当月是否已经有记录
          $code = AssetNumberIncrease::where('year_month', '=', $year_month)->lock(true)->value('code');//行锁
          if ($code) { //存在记录，那就更新
          $code = intval($code) + 1;
          $code = sprintf('%03d', $code);
          AssetNumberIncrease::where('year_month', '=', $year_month)->update(['code' => $code]);
          } else { //不存在，那就新增
          $code = '001';
          AssetNumberIncrease::insert(['year_month' => $year_month, 'code' => $code]);
          }
          $code = 'CEB' . $year_month . $code;

          // 提交事务
          Db::commit();
          } catch (\Exception $e) {
          // 回滚事务
          Db::rollback();
          return $this->error('失败原因：' . $e->getMessage());
          }
         */
        //先查找当月是否已经有记录
        $code = AssetNumberIncrease::where('year_month', '=', $year_month)->value('code');
        if ($code) { //存在记录，那就更新
            $code = intval($code) + 1;
            $code = sprintf('%03d', $code);
            AssetNumberIncrease::where('year_month', '=', $year_month)->update(['code' => $code]);
        } else { //不存在，那就新增
            $code = '001';
            AssetNumberIncrease::insert(['year_month' => $year_month, 'code' => $code]);
        }
        //不用行锁，改用4位随机字母
        $str_random = '';
        for ($i = 1; $i <= 4; $i++) {
         $str_random .= chr(rand(97, 122));
        }
        
        $code = 'CEB' . $year_month . $code . strtoupper($str_random);
        $this->assign('code', $code);

        //还款方式
        $repayment_type_list = TpAssets::getRepaymentTypeList();
        $this->assign('repayment_type_list', $repayment_type_list);

        if ($type == TpAssets::TYPE_CAR) { //车贷
            return view('Assets/add_car2');
        } elseif ($type == TpAssets::TYPE_CONSUME) { //消费贷
            return view('Assets/add_consume');
        } elseif ($type == TpAssets::TYPE_ENTERPRISE) { //企业贷
            return view('Assets/add_enterprise');
        }
    }

    /**
     * 最终添加资产
     */
    public function doAdd()
    {
        $user_id = $this->_Uid;

        $ids = input('user_ids/a'); //数组一定要加上/a
        $name = input('name/s');
        $code = input('code/s');
        $capital = input('capital/f');
        $type = input('type/d');
        $duration = input('duration/d');
        $interest_rate = input('interest_rate/f');
        $repayment_type = input('repayment_type/d');
        $service_amount_type = input('service_amount_type/d');
        $marketing_fee = input('marketing_fee/f');
        $service_remarks = input('service_remarks/s');
        $contract_time_start = input('contract_time_start/s');
        $contract_time_end = input('contract_time_end/s');
                
        //请求参数校验
        $rule = [
            'ids'  => 'require',
            'name'  => 'require',
            'code'  => 'require',
            'capital'  => 'require|number',
            'type'  => 'require|number',
            'duration'  => 'require|number',
            'interest_rate'  => 'require',
            'repayment_type'  => 'require|number',
            'service_amount_type'  => 'require',
            'contract_time_start'  => 'require',
            'contract_time_end'  => 'require',
        ];

        $data = [
            'ids'  => $ids,
            'name'  => $name,
            'code'  => $code,
            'capital'  => $capital,
            'type'  => $type,
            'duration'  => $duration,
            'interest_rate'  => $interest_rate,
            'repayment_type'  => $repayment_type,
            'service_amount_type'  => $service_amount_type,
            'contract_time_start'  => $contract_time_start,
            'contract_time_end'  => $contract_time_end,
        ];

        $validate = new Validate($rule);
        $result   = $validate->check($data);

        if(!$result){
            $this->error($validate->getError());
        }
        

        $now = time();

        // 启动事务
        Db::startTrans();
        try {
            unset($data['ids']);
            $data_assets = $data;
            $data_assets['created_at'] = $now;
            $data_assets['marketing_fee'] = $marketing_fee;
            $data_assets['service_remarks'] = $service_remarks;
            $data_assets['contract_time_start'] = strtotime($contract_time_start);
            $data_assets['contract_time_end'] = strtotime($contract_time_end);
            $data_assets['status'] = TpAssets::STATUS_CHECK;
            $data_assets['merchant_id'] = $user_id;
            
//            $duration = input('duration/d');
//            $data_assets = [
//                'name' => input('name/s'),
//                'code' => input('code/s'),
//                'capital' => input('capital/f'),
//                'type' => input('type/d'),
//                'status' => TpAssets::STATUS_CHECK,
//                'merchant_id' => $user_id,
//                'duration' => $duration,
//                'interest_rate' => input('interest_rate/f'),
//                'repayment_type' => input('repayment_type/d'),
//                'created_at' => $now,
//                'service_amount_type' => input('service_amount_type/d'),
//                'marketing_fee' => input('marketing_fee/f'),
//                'service_remarks' => input('service_remarks/s'),
//                'contract_time_start' => strtotime(input('contract_time_start/s')),
//                'contract_time_end' => strtotime(input('contract_time_end/s')),
//            ];
            //主表添加数据
            $assets_id = TpAssets::insertGetId($data_assets);

            //详情表添加数据
            $ids_str = implode(',', $ids);
            $borrows = BorrowRequest::alias('br')
                    ->join('tp_user tu', 'br.borrow_uid = tu.uid')
                    ->where("br.id in ($ids_str)")
                    ->field('br.*, tu.real_name')
                    ->select();
            $data_detail = [];
            foreach ($borrows as $borrow) {
                $temp = [
                    'assets_id' => $assets_id,
                    'request_id' => $borrow['id'],
                    'borrower_name' => $borrow['real_name'],
                    'borrower_uid' => $borrow['borrow_uid'],
                    'amount' => $borrow['money'],
                    'duration' => $borrow['duration'],
                    'created_at' => $now,
                ];
                $data_detail[] = $temp;
            }
            TpAssetsDetail::insertAll($data_detail);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('添加失败，原因如下：' . $e->getMessage());
        }

        $this->success('添加成功', 'Assets/index');
    }

}
